package com.cinema.dao.impl;

import com.cinema.dao.UserDao;
import com.cinema.model.User;
import com.cinema.model.UserType;
import com.cinema.util.SimpleFileUtil;
import com.cinema.util.LogUtil;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户数据访问实现类
 * 使用简单文本文件存储用户数据
 */
public class UserDaoImpl implements UserDao {
    
    private static final String USER_FILE = "users.txt";
    private static final String DEFAULT_PASSWORD = "123456";
    private List<User> users;
    
    public UserDaoImpl() {
        loadUsers();
        initDefaultAdmin();
    }
    
    /**
     * 加载用户数据
     */
    private void loadUsers() {
        users = new ArrayList<>();
        List<String> lines = SimpleFileUtil.readListFromFile(USER_FILE);
        
        for (String line : lines) {
            User user = parseUserFromLine(line);
            if (user != null) {
                users.add(user);
            }
        }
    }
    
    /**
     * 保存用户数据到文件
     */
    private void saveUsers() {
        List<String> lines = new ArrayList<>();
        for (User user : users) {
            lines.add(formatUserToLine(user));
        }
        SimpleFileUtil.saveListToFile(USER_FILE, lines);
    }
    
    /**
     * 将用户对象格式化为文本行
     * 格式：userId|username|password|phoneNumber|userType|registrationTime|needPasswordChange
     */
    private String formatUserToLine(User user) {
        return String.join("|",
            user.getUserId(),
            user.getUsername(),
            user.getPassword(),
            user.getPhoneNumber(),
            user.getUserType().name(),
            SimpleFileUtil.formatDateTime(user.getRegistrationTime()),
            String.valueOf(user.isNeedPasswordChange())
        );
    }
    
    /**
     * 从文本行解析用户对象
     */
    private User parseUserFromLine(String line) {
        try {
            String[] parts = line.split("\\|");
            if (parts.length != 7) {
                return null;
            }
            
            User user = new User();
            user.setUserId(parts[0]);
            user.setUsername(parts[1]);
            user.setPassword(parts[2]);
            user.setPhoneNumber(parts[3]);
            user.setUserType(UserType.valueOf(parts[4]));
            user.setRegistrationTime(SimpleFileUtil.parseDateTime(parts[5]));
            user.setNeedPasswordChange(Boolean.parseBoolean(parts[6]));
            
            return user;
        } catch (Exception e) {
            LogUtil.logError("用户数据解析", "解析用户数据失败: " + line + " - " + e.getMessage());
            return null;
        }
    }
    
    /**
     * 初始化默认管理员账户
     */
    private void initDefaultAdmin() {
        // 检查是否已存在admin账户
        if (findByUsername("admin") == null) {
            String adminId = generateUserId();
            User admin = new User(adminId, "admin", "ynuinfo#777", "13800000000", UserType.ADMIN);
            admin.setNeedPasswordChange(false); // admin账户不需要强制修改密码
            users.add(admin);
            saveUsers();
            LogUtil.logOperation("系统初始化", "system", "创建默认管理员账户: admin");
        }
    }
    
    /**
     * 生成唯一用户ID
     */
    private String generateUserId() {
        String userId;
        do {
            userId = "U" + String.format("%06d", (int)(Math.random() * 1000000));
        } while (existsById(userId));
        return userId;
    }
    
    @Override
    public boolean save(User user) {
        try {
            // 检查唯一性约束
            if (existsById(user.getUserId())) {
                LogUtil.logError("用户保存", "用户ID已存在: " + user.getUserId());
                return false;
            }
            if (existsByUsername(user.getUsername())) {
                LogUtil.logError("用户保存", "用户名已存在: " + user.getUsername());
                return false;
            }
            if (existsByPhoneNumber(user.getPhoneNumber())) {
                LogUtil.logError("用户保存", "手机号已存在: " + user.getPhoneNumber());
                return false;
            }
            
            // 如果没有设置ID，自动生成
            if (user.getUserId() == null || user.getUserId().isEmpty()) {
                user.setUserId(generateUserId());
            }
            
            // 如果没有设置注册时间，设置为当前时间
            if (user.getRegistrationTime() == null) {
                user.setRegistrationTime(LocalDateTime.now());
            }
            
            users.add(user);
            saveUsers();
            return true;
            
        } catch (Exception e) {
            LogUtil.logError("用户保存", "保存用户失败: " + e.getMessage());
            return false;
        }
    }
    
    @Override
    public User findById(String userId) {
        return users.stream()
                .filter(user -> user.getUserId().equals(userId))
                .findFirst()
                .orElse(null);
    }
    
    @Override
    public User findByUsername(String username) {
        return users.stream()
                .filter(user -> user.getUsername().equals(username))
                .findFirst()
                .orElse(null);
    }
    
    @Override
    public User findByPhoneNumber(String phoneNumber) {
        return users.stream()
                .filter(user -> user.getPhoneNumber().equals(phoneNumber))
                .findFirst()
                .orElse(null);
    }
    
    @Override
    public boolean update(User user) {
        try {
            for (int i = 0; i < users.size(); i++) {
                if (users.get(i).getUserId().equals(user.getUserId())) {
                    // 检查唯一性约束（排除自己）
                    User existingByUsername = findByUsername(user.getUsername());
                    if (existingByUsername != null && !existingByUsername.getUserId().equals(user.getUserId())) {
                        LogUtil.logError("用户更新", "用户名已存在: " + user.getUsername());
                        return false;
                    }
                    
                    User existingByPhone = findByPhoneNumber(user.getPhoneNumber());
                    if (existingByPhone != null && !existingByPhone.getUserId().equals(user.getUserId())) {
                        LogUtil.logError("用户更新", "手机号已存在: " + user.getPhoneNumber());
                        return false;
                    }
                    
                    users.set(i, user);
                    saveUsers();
                    return true;
                }
            }
            return false;
            
        } catch (Exception e) {
            LogUtil.logError("用户更新", "更新用户失败: " + e.getMessage());
            return false;
        }
    }
    
    @Override
    public boolean delete(String userId) {
        try {
            // 不能删除admin账户
            User user = findById(userId);
            if (user != null && "admin".equals(user.getUsername())) {
                LogUtil.logError("用户删除", "不能删除admin管理员账户");
                return false;
            }
            
            boolean removed = users.removeIf(u -> u.getUserId().equals(userId));
            if (removed) {
                saveUsers();
            }
            return removed;
            
        } catch (Exception e) {
            LogUtil.logError("用户删除", "删除用户失败: " + e.getMessage());
            return false;
        }
    }
    
    @Override
    public List<User> findAll() {
        return new ArrayList<>(users);
    }
    
    @Override
    public List<User> findByUserType(UserType userType) {
        return users.stream()
                .filter(user -> user.getUserType() == userType)
                .collect(Collectors.toList());
    }
    
    @Override
    public boolean existsByUsername(String username) {
        return users.stream().anyMatch(user -> user.getUsername().equals(username));
    }
    
    @Override
    public boolean existsById(String userId) {
        return users.stream().anyMatch(user -> user.getUserId().equals(userId));
    }
    
    @Override
    public boolean existsByPhoneNumber(String phoneNumber) {
        return users.stream().anyMatch(user -> user.getPhoneNumber().equals(phoneNumber));
    }
    
    @Override
    public User validateLogin(String username, String password) {
        User user = findByUsername(username);
        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        return null;
    }
    
    @Override
    public boolean changePassword(String userId, String newPassword) {
        try {
            User user = findById(userId);
            if (user != null) {
                user.setPassword(newPassword);
                user.setNeedPasswordChange(false);
                return update(user);
            }
            return false;
            
        } catch (Exception e) {
            LogUtil.logError("密码修改", "修改密码失败: " + e.getMessage());
            return false;
        }
    }
    
    @Override
    public boolean resetPassword(String userId) {
        try {
            User user = findById(userId);
            if (user != null) {
                user.setPassword(DEFAULT_PASSWORD);
                user.setNeedPasswordChange(true);
                return update(user);
            }
            return false;
            
        } catch (Exception e) {
            LogUtil.logError("密码重置", "重置密码失败: " + e.getMessage());
            return false;
        }
    }
    
    @Override
    public int getUserCount() {
        return users.size();
    }
    
    @Override
    public int getUserCountByType(UserType userType) {
        return (int) users.stream()
                .filter(user -> user.getUserType() == userType)
                .count();
    }
    
    /**
     * 重新加载用户数据（用于数据同步）
     */
    public void reload() {
        loadUsers();
    }
    
    /**
     * 获取下一个可用的用户ID
     */
    public String getNextUserId() {
        return generateUserId();
    }
    
    /**
     * 批量保存用户
     */
    public boolean saveAll(List<User> userList) {
        try {
            // 验证所有用户的唯一性
            for (User user : userList) {
                if (existsById(user.getUserId()) || 
                    existsByUsername(user.getUsername()) || 
                    existsByPhoneNumber(user.getPhoneNumber())) {
                    LogUtil.logError("批量保存用户", "存在重复的用户信息");
                    return false;
                }
            }
            
            users.addAll(userList);
            saveUsers();
            return true;
            
        } catch (Exception e) {
            LogUtil.logError("批量保存用户", "批量保存失败: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 清空所有用户（谨慎使用）
     */
    public boolean clearAll() {
        try {
            users.clear();
            saveUsers();
            initDefaultAdmin(); // 重新创建默认管理员
            return true;
            
        } catch (Exception e) {
            LogUtil.logError("清空用户", "清空用户数据失败: " + e.getMessage());
            return false;
        }
    }
}